<template>
  <by-background />

  <by-navigation-bar :title="titles[type]"/>

  <view class="flex-row justify-between padding-tb-36 bg-white">
    <view v-for="(item,index) in flow" :key="index" class="flow-item flex-column flex-center flex-item">
      <view class="image margin-bottom-20 relative" :class="{'line': index}">
        <image class="width-full height-full" :src="`/static/flow/${item.img}`" />
      </view>
      <text class="text-26 color-t2">{{item.label}}</text>
    </view>
  </view>

  <view class="padding-lr-20 padding-bottom-20">
    <by-list-card :item="technicianInfo" :showContact="false" type="subscribe" />

    <view class="info-card margin-top-20">
      <by-title title="预约备注" />
      <view class="padding-tb-30">
        <view class="textarea-box">
          <textarea
            :value="subscribeInfo.userRemark"
            :maxlength="100"
            :disabled="type"
            placeholder="请输入预约备注（请勿备注敏感信息，违禁违规信息）"
            placeholder-style="color: #B7B7B7"
            class="textarea width-full text-28 color-t1"
            @input="userStore.subscribeInfo.userRemark = $event.detail.value"
          />
        </view>
      </view>
    </view>

    <view class="info-card margin-top-20">
      <by-title v-if="subscribeInfo.username">
        <view class="flex-row align-center">
          <text class="text-32 color-t1">{{ type ? '' : '您的' }}联系信息</text>
          <text class="text-28 color-t2">（确保准确）</text>
        </view>
        <template v-if="!type" #right>
          <view class="flex-row align-center" hover-class="opacity-hover" :hover-stay-time="70" :hover-start-time="20" @click="jump('/pages/set-subscribe-info/index')">
            <image src="/static/edit.png" class="edit margin-right-10" />
            <text class="text-28 color-fourth">修改</text>
          </view>
        </template>
      </by-title>
      <by-title v-else title="请添加联系方式与地址" :border="false"  @click="jump('/pages/set-subscribe-info/index')">
        <template #right>
          <text class="technician-fanhui text-20 color-t2"></text>
        </template>
      </by-title>
      <view v-if="subscribeInfo.username" class="padding-30 flex-column text-28 color-t2">
        <text>联系人：{{subscribeInfo.username}}（{{subscribeInfo.userGender == 1 ? '女士' : '先生' }}）</text>
        <text v-if="subscribeInfo.userTel" class="margin-top-20">手机号：{{subscribeInfo.userTel}}</text>
        <text v-if="subscribeInfo.userWx" class="margin-top-20">微信号：{{subscribeInfo.userWx}}</text>
<!--        <text class="margin-top-20">服务时间：{{dateFormat(subscribeInfo.serviceTimeStr || subscribeInfo.serviceTime,'MM月DD日 hh:mm')}}</text>
        <text class="margin-top-20">服务地址：{{subscribeInfo.userAddress}}{{subscribeInfo.userAddressSecond}}</text>-->
      </view>
    </view>

    <view class="margin-top-26 padding-lr-20 flex-column tips">
      <text class="text-28">温馨提示：</text>
      <text class="text-28">1. 免费上门见面付，技师上门后当面确认服务项目，如不满意可以重新预约（预约较远技师，往返车费双方自行协商）。</text>
      <text class="text-28">2. 预约技师失败或未接单，免费取消预约积分退还，可以重新预约。</text>
      <text class="text-28">3. 技师接单后，通常会在15分钟内联系，也可免费联系技师，技师出发前会与您核实预约信息，请保持通讯畅通。</text>
      <text class="text-28">4. 平台禁止一切违禁违规信息等行为。如遇虚假，欺诈等不良行为，请立即向平台投诉。</text>
    </view>
  </view>

  <view class="padding-20">
    <view style="height: 78rpx;" />
  </view>
  <safe-area-bottom />

  <view class="footer">
    <view class="bottom padding-20 bg-white flex-row justify-between align-center">
      <view v-if="!type" class="flex-column">
        <text class="text-32 color-fourth">{{price.billPoint}}积分</text>
        <text v-if="!isTechnician" class="text-24 color-t3">剩余：{{price.userPoint}}积分</text>
      </view>
      <text v-if="appointmentDetail.status === 0" class="text-28 color-fourth">等待接单</text>
      <text v-if="appointmentDetail.status === 1" class="text-28 color-success">已接单</text>
      <text v-if="appointmentDetail.status === -1" class="text-28 color-grey">已取消</text>
      <text v-if="appointmentDetail.status === -2" class="text-28 color-error">已拒绝</text>

      <view class="flex-row">
        <template v-if="!type">
          <view v-if="isShowContact" class="margin-right-20">
            <by-button width="240rpx" height="78rpx" bold text="立即联系" @click="handleShowContact"/>
          </view>
          <by-button width="240rpx" height="78rpx" bold background="#FD8300" font-color="#ffffff" text="确认预约" @click="submit"/>
        </template>
        <template v-else-if="isTechnician">
          <template v-if="appointmentDetail.status === 0">
            <view class="margin-right-20">
              <by-button width="240rpx" height="78rpx" bold text="立即接单" @click="setStatus(1)"/>
            </view>
            <by-button width="240rpx" height="78rpx" bold background="#FD8300" font-color="#ffffff" text="拒绝接单" @click="setStatus(-2)"/>
          </template>
        </template>
        <template v-else>
          <view v-if="isShowContact" class="margin-right-20">
            <by-button width="240rpx" height="78rpx" bold text="立即联系" @click="handleShowContact"/>
          </view>
          <by-button v-if="appointmentDetail.status === 0" width="240rpx" height="78rpx" bold background="#FD8300" font-color="#ffffff" text="取消预约" @click="setStatus(-1)"/>
        </template>
      </view>
    </view>
    <safe-area-bottom />
  </view>

  <by-page-dialogs
    :type="showType"
    v-model:show-touch="showTouch"
    v-model:show-contact-way="showContactWay"
    v-model:show-error="showError"
    :point="point"
    :tno="tno"
    @showContact="showContactWay = true"
    @submitSubscribe="confirmSubscribe"
  />

  <by-dialog v-model="showDialog" title="提示" :content="content" @confirm="handleUpdateStateServiceAppointment"/>
</template>

<script setup lang="ts">
import useUserStore from '@/store/user'
import { jump, dateFormat, toast, copyData } from '@/common/util'
import { getTechnicianDetail, getBillPoint, isUnlockContact, addServiceAppointment, getServiceAppointmentDetail, updateStateServiceAppointment } from '@/common/api'
import type { AnyObject } from '@/common/types'

const userStore = useUserStore()

const flow = [
  { label: '预约', img: 'increase.png' },
  { label: '技师接单', img: 'receive.png' },
  { label: '见面支付', img: 'pay.png' },
  { label: '完成服务', img: 'complete.png' },
  { label: '评价', img: 'evaluate.png' }
]

const titles = ['预约上门', '预约详情']
const type = ref(0)
const tno = ref('')
const isTechnician = ref(false)
const subscribeInfo = computed(() => appointmentDetail.value.appointmentNo ? appointmentDetail.value : userStore.subscribeInfo)
let appointmentNo = ''
let serviceNo = ''
onLoad((e) => {
  if (e?.type) type.value = e.type
  if (e?.tno) tno.value = e.tno
  if (e?.serviceNo) serviceNo = e.serviceNo
  if (e?.appointmentNo) {
    appointmentNo = e.appointmentNo
    handleGetServiceAppointmentDetail()
  } else handleGetBillPoint()
  isTechnician.value = !!e?.js
  getDetail()
})

/**
 * 获取预约详情 start
 * */
const appointmentDetail = shallowRef<AnyObject>({})
async function handleGetServiceAppointmentDetail() {
  const res = await getServiceAppointmentDetail({ appointmentNo })
  const { data } = res
  appointmentDetail.value = data
}
/**
 * 获取预约详情 end
 * */

/**
 * 修改预约状态 start
 * */
const showDialog = ref(false)
const content = ref('')
let status = 0
function setStatus(value:number) {
  status = value
  showDialog.value = true
  if (value === -1) content.value = '确认取消预约？'
  if (value === -2) content.value = '确认拒绝预约？'
  if (value === 1) content.value = '确认接受预约？'
}

async function handleUpdateStateServiceAppointment() {
  await updateStateServiceAppointment({
    appointmentNo,
    status
  })
  if (status === -1) toast('取消成功')
  if (status === -2) toast('预约已拒绝')
  if (status === 1) toast('预约已接受')
  handleGetServiceAppointmentDetail()
}
/**
 * 修改预约状态 end
 * */

/**
 * 获取技师信息 start
 * */
const technicianInfo = shallowRef({})
async function getDetail() {
  const res = await getTechnicianDetail({
    tno: tno.value,
    ...userStore.location
  })
  technicianInfo.value = res.data.technician
}
/**
 * 获取技师信息 end
 * */

/**
 * 获取预约价格 start
 * */
interface IPrice{
  billPoint: number
  userPoint: number
}
const price = shallowRef<IPrice>({
  billPoint: 0,
  userPoint: 0
})

async function handleGetBillPoint() {
  const res = await getBillPoint('appointment')
  price.value = res.data
}
/**
 * 获取预约价格 end
 * */

/**
* 底部按钮 start
* */
const showContactWay = ref(false)
const point = ref(0)
const showTouch = ref(false)
const showError = ref(false)
const showType = ref('')
const isShowContact = ref(true)

/* #ifdef APP-PLUS*/
import useSystemStore from '@/store/system'
import { getHonorAuditConfig } from '@/common/api'
const systemStore = useSystemStore()
async function handleGetHonorAuditConfig() {
  const res = await getHonorAuditConfig()
  const { isAudit } = res.data
  if (systemStore.systemInfo.brand === 'honor' || systemStore.systemInfo.brand === 'huawei' || systemStore.systemInfo.brand === 'vivo') isShowContact.value = !isAudit
}
handleGetHonorAuditConfig()
/* #endif*/

// 提交预约
function submit() {
  if (!subscribeInfo.value.username) {
    toast('请先完善您的联系信息')
    return
  }
  showType.value = '1'
  point.value = price.value.billPoint
  if (price.value.billPoint > price.value.userPoint) showError.value = true
  else showTouch.value = true
}

// 确认预约
async function confirmSubscribe() {
  const form = copyData(subscribeInfo.value)
  const year = new Date().getFullYear()
  form.serviceTimeStr = year + '-' + form.serviceTimeStr
  console.log({
    serviceNo,
    tno: tno.value,
    ...form
  })
  await addServiceAppointment({
    serviceNo,
    tno: tno.value,
    ...form
  })
  jump()
  toast('预约成功')
}

// 联系技师
async function handleShowContact() {
  showType.value = ''
  if (!userStore.token) {
    jump('login')
    toast('请先登录')
    return
  }
  const info = await isUnlockContact(tno.value)
  const { data } = info
  data.canGet = data.userPoint - data.unlockPoint >= 0
  if (data.unlock) {
    showContactWay.value = true
  } else {
    point.value = data.unlockPoint
    if (data.canGet) showTouch.value = true
    else showError.value = true
  }
}
/**
 * 底部按钮 end
 * */

/**
 * 返回监听 start
 * */
const back = computed(() => showTouch.value || showContactWay.value || showError.value)
onBackPress(() => {
  if (back.value) {
    close()
    return true
  }
})
function close() {
  showTouch.value = showContactWay.value = showError.value = false
}
onHide(close)
/**
 * 返回监听 end
 * */
</script>

<style scoped lang="scss">
@include setPadding(tb, 36);

@include setMargin(top, 26);

.flow-item{

  .image{
    width: 60rpx;
    height: 60rpx;

    &.line:after{
      content:'';
      display: block;
      width: 62rpx;
      height: 2rpx;
      background: #FDDA26;
      position: absolute;
      left: -76rpx;
      top: 30rpx;
    }

  }

}

.info-card{
  background: $color-white;
  border-radius: 16rpx;
  padding: 6rpx 20rpx;

  .technician-fanhui{
    display: block;
    transform: rotate(180deg);
  }

}

.textarea-box{
  height: 200rpx;
  background: #F7F8F9;
  border-radius: 16rpx;
  padding: 24rpx;
}

.edit{
  width: 36rpx;
  height: 30rpx;
}

.tips{
  color: #B7B7B7;
}

.footer{
  position: fixed;
  bottom: 0;
  left: 0;
  width: 750rpx;

  .color-t3{
    color: #999999;
  }

}
</style>
